package com.imist.core;

import com.imist.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("login - 1.preHandle");

        User user = (User) request.getSession().getAttribute("session_user");
        //若是User对象为null，代表用户没有登录，直接重定向到登录页面
        if (user == null){
            //这里重定向需要绝对路径
           response.sendRedirect(request.getContextPath()+"/login");
           return false; //会终止所有的请求,接下来的方法不会执行
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("login - 3.postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("login -  4.afterCompletion");
    }
}
